package com.tjb;

import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.exception.write.WriteProcessException;
import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.fileSystem.FSFactoryProducer;
import org.apache.tsfile.read.common.Path;
import org.apache.tsfile.write.TsFileWriter;
import org.apache.tsfile.write.record.TSRecord;
import org.apache.tsfile.write.record.datapoint.DoubleDataPoint;
import org.apache.tsfile.write.schema.MeasurementSchema;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

/**
 * @author tjb
 * @version 1.0
 * @date 2024/6/5 21:10
 */
public class TsFileWriteWithTSRecord {
  /**
   * 将文件写成TsFile
   * @param objList ： 数据文件
   * @param path : 路径
   * @return : 返回成功与失败
   */
  public static boolean writeFileToTsFile(List<TsFileEntity> objList,List<String> HeaderName, String path) {
    System.out.println("开始进入文件写入流程");
    System.out.println("文件处理--------");
    //1、路径判断
    if (path == null || objList.size() < 1){
      return false;
    }
    //2、执行流程
    try {
      //2.1、存在文件就先删除文件
      File f = FSFactoryProducer.getFSFactory().getFile(path);
      if (f.exists()) {
        Files.delete(f.toPath());
      }
      //开始写的流程
      try (TsFileWriter tsFileWriter = new TsFileWriter(f)) {
        System.out.println("创建序列-------");
        //2.2、挂载的类型，根据自己的情况而定
        MeasurementSchema measurementSchema = new MeasurementSchema(HeaderName.get(1), TSDataType.DOUBLE, TSEncoding.PLAIN);
        //挂载到tsFileWriter
        tsFileWriter.registerTimeseries(new Path("root.ln.tjb"), measurementSchema);
        // 3、写入数据
        write(tsFileWriter,HeaderName, objList);
      }
    } catch (Exception e) {
      System.out.println("TsFileWriteWithTSRecord meet error: " + e);
      return false;
    }
    //3、返回
    return true;
  }

  /**
   * 写入数据到文件中
   * @param tsFileWriter : write
   * @param  : 类型挂载
   * @param objList : 要写的数据集
   * @throws IOException
   * @throws WriteProcessException
   */
  private static void write(TsFileWriter tsFileWriter, List<String> HeaderName,List<TsFileEntity> objList) throws IOException, WriteProcessException, InterruptedException {
    System.out.println("写入数据----");
    //1、在遍历过程中封装TsRecord对象，然后写入文件中
    for (TsFileEntity tsFileEntity : objList) {
      //2、构造TsRecord
      Thread.sleep(10);
      TSRecord tsRecord = new TSRecord(System.currentTimeMillis(),"root.ln.tjb");
      DoubleDataPoint doubleDataPoint = new DoubleDataPoint(HeaderName.get(1), tsFileEntity.getValue());
      tsRecord.addTuple(doubleDataPoint);
      // 3、写入
      tsFileWriter.write(tsRecord);
    }
  }
}